import Vue from 'vue'
import Vuex from 'vuex'
import * as Types from './mutation-types'
import * as apis from '@/api/api.js'
import { isH5 } from '@/env'
import { showToast } from '@/common/utils/toast'
import config from '@/config'
import { AssetMap } from '../common/constants/assetMap'
import { isLocal } from '../env'
import { APIRequest } from '@/api/index'
import pops from './modules/pops'
import { getTableConfig } from '../common/utils/getTable'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    pops,
  },
  state: {
    // 渠道参数，来自url带参
    channel: '',
    // 聚合登录信息
    multiLoginInfo: null,
    isLogin: false,
    // 业务登录信息
    loginInfo: null,
    assetMap: AssetMap,
    navBarInfo: {},
    systemInfo: {},
    versionInfo: {},
    wxSetting: null,
    isErrorPage: true,
    wxSettingFetchTimes: 0, // 获取微信设置的次数
    maxWxSettingFetchTimes: 3, // 最大获取微信设置的次数
    tableConfigData: null, // 配表数据
    userInfo: {},
  },
  mutations: {
    [Types.SET_CHANNEL](state, channel) {
      state.channel = channel
    },
    [Types.FETCH_ASSET_MAP](state, data) {
      state.assetMap = data
    },
    [Types.SET_MUTI_LOGIN_INFO](state, info) {
      state.multiLoginInfo = info || null
    },
    [Types.SET_ERROR_PAGE](state, data) {
      state.isErrorPage = data
    },
    [Types.SET_SYSTEM_INFO](state, data) {
      state.systemInfo = data
    },
    [Types.SET_NAVBAR_INFO](state, data) {
      state.navBarInfo = data
    },
    [Types.SET_APP_VERSION](state, data) {
      state.versionInfo = data
    },
    [Types.SET_WX_SETTING](state, data) {
      console.log('setWxSetting')
      state.wxSetting = data
    },
    [Types.SET_WX_SETTING_FETCH_TIMES](state, data) {
      console.log('setWxSettingTimes')
      state.wxSettingFetchTimes = data
    },
    [Types.SET_USER_INFO](state, data) {
      state.userInfo = data
    },
    [Types.SET_TABLE_CONF](state, data) {
      state.tableConfigData = data
    },
    [Types.SET_IS_LOGIN](state, data) {
      state.isLogin = data
    },
    [Types.SET_ERROR_PAGE](state, data) {
      state.isErrorPage = data
    },
  },
  actions: {
    fetchTableData(context, useLocalCache) {
      return getTableConfig(useLocalCache)
    },
    fetchAssetMap(context) {
      if (isLocal()) {
        return
      }
      uni.request({
        url: process.env.VUE_APP_ASSET_MAP_PATH,
        success: (res) => {
          context.commit(Types.FETCH_ASSET_MAP, res.data)
        },
        fail: (err) => {
          console.error('fetchAssetMapError', err)
        },
      })
    },
    async setPageError(context, isError) {
      console.log('error', isError)
      context.commit(Types.SET_ERROR_PAGE, isError)
    },
    fetchAppVersion(context) {
      const appVersion = uni.getSystemInfoSync().appVersion
      context.commit(Types.SET_APP_VERSION, appVersion)
    },
    setNavBarInfo(context) {
      // #ifdef MP-WEIXIN
      const info = uni.getSystemInfoSync()
      const safeTop = uni.getWindowInfo().safeArea?.top
      console.log('safeTop', safeTop)
      context.commit(Types.SET_SYSTEM_INFO, info)
      // 胶囊按钮位置信息
      const { statusBarHeight } = info
      const { width, height, top, right } = uni.getMenuButtonBoundingClientRect()
      const navBarHeight = (top - statusBarHeight) * 2 + height + statusBarHeight
      const menuBottom = top - statusBarHeight
      const menuRight = info.screenWidth - right
      context.commit(Types.SET_NAVBAR_INFO, {
        WH: info.screenWidth / info.screenHeight,
        safeTop,
        statusBarHeight,
        navBarHeight,
        menuBottom,
        menuRight,
        menuWidth: width,
        menuHeight: height,
      })
      // #endif
      // #ifdef H5
      context.commit(Types.SET_NAVBAR_INFO, {
        WH: 499 / 1624,
        safeTopL: 0,
        statusBarHeight: 44,
        navBarHeight: 44,
        menuBottom: 4,
        menuRight: 7,
        menuWidth: 87,
        height: 32,
      })
      // #endif
    },
    async fetchUserInfo(context) {
      // TODO: change to real api logic
      try {
        if (!isH5()) {
          const tokenResult = await apis.getAuthToken(config.activityId)
          APIRequest.setToken(tokenResult.token)
        }
        const userInfo = await apis.getUserInfo()
        context.commit(Types.SET_USER_INFO, userInfo)
        context.commit(Types.SET_IS_LOGIN, true)
        return Promise.resolve(userInfo)
      } catch (e) {
        if (isH5() && e.code === -401) {
          showToast('登录信息已过期，请重新登录', 3000)
        }
        context.commit(Types.SET_IS_LOGIN, false)
        return Promise.reject(e)
      }
    },
  },
})
export default store
